import { findDomByVNode, updateDomTree } from "./react-dom"

export let updaterQueue = {
    isBatch: false,
    updaters: new Set()
}

// 清空批量更新队列
export function flushUpdaterQueue() {
    updaterQueue.isBatch = false
    updaterQueue.updaters.forEach(updater => updater.lanuchUpadate())
    updaterQueue.updaters.clear()
}

// 更新器（管理状态用的）
class Updater {
    constructor(ClassComponentInstance) {
        // 实例
        this.ClassComponentInstance = ClassComponentInstance
        this.pendingStates = []
    }
    addState(partialState) {
        this.pendingStates.push(partialState)
        // 预处理器
        this.preHandleForUpdate()
    }

    // 预处理器
    preHandleForUpdate() {
        if (updaterQueue.isBatch) {
            updaterQueue.updaters.add(this)
        } else {
            this.lanuchUpadate()
        }
    }
    lanuchUpadate() {
        const { ClassComponentInstance, pendingStates } = this
        if (!pendingStates.length) {
            return
        }
        // 属性状态进行合并
        ClassComponentInstance.state = this.pendingStates.reduce((acc, cur) => {
            return { ...acc, ...cur }
        }, ClassComponentInstance.state)
        this.pendingStates.length = 0
        ClassComponentInstance.update()
    }
}

export class Component {
    static IS_CLASS_COMPONENT = true
    constructor(props) {
        this.Updater = new Updater(this)
        this.state = {}
        this.props = props;
    }

    setState(partialState) {
        // 合并属性
        // this.state = {...this.state, ...partialState}
        // // 更新
        // this.update()
        this.Updater.addState(partialState)
    }

    update() {
        // 获取重新执行render函数后的虚拟dom 渲染后的虚拟dom
        // 根据新虚拟dom生成新的真实dom
        // 将真实dom挂载到页面上
        let oldVNode = this.oldVNode
        let oldDOM = findDomByVNode(oldVNode)
        let newVNode = this.render()
        updateDomTree(oldDOM, newVNode)
        this.oldVNode = newVNode
    }
}